package com.yunxi.service.dubboService.impl.sto;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.yunxi.core.page.PageHelperPlus;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.freeze.service.PartnerAmountFreezeFlowDubboService;
import com.yunxi.model.order.OrderVehicle;
import com.yunxi.model.order.PmsVehicleStock;
import com.yunxi.model.sto.StoManage;
import com.yunxi.model.sto.StoStockOutPlan;
import com.yunxi.model.sto.StoStorageStaff;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.sat.pojo.SatMessAddVO;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.OrderVehicleService;
import com.yunxi.service.localService.sat.SatMessService;
import com.yunxi.service.localService.sto.*;
import com.yunxi.sto.pojo.*;
import com.yunxi.sto.service.StoStockOutPlanDubboService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 车辆出库计划单 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-05-20
 */
public class StoStockOutPlanDubboServiceImpl implements StoStockOutPlanDubboService {

    @Autowired
    @Qualifier(value = "stoStockOutPlanServiceImpl")
    StoStockOutPlanService stoStockOutPlanService;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService codeCreateService;

    @Autowired
    @Qualifier(value = "vehicleStockMServiceImpl")
    VehicleStockMService vehicleStockMService;
    
    @Autowired
    @Qualifier(value = "stoManageServiceImpl")
    StoManageService stoManageService;

    @Autowired
    @Qualifier(value = "partnerAmountFreezeFlowDubboServiceImpl")
    PartnerAmountFreezeFlowDubboService partnerAmountFreezeFlowDubboService;

    @Autowired
    @Qualifier(value = "vehiclePdiBillServiceImpl")
    VehiclePdiBillService vehiclePdiBillService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    @Autowired
    @Qualifier(value = "orderVehicleServiceImpl")
    OrderVehicleService orderVehicleService;

    @Autowired
    @Qualifier(value = "satMessServiceImpl")
    SatMessService satMessService;

    @Autowired
    @Qualifier(value = "stoStorageStaffServiceImpl")
    StoStorageStaffService stoStorageStaffService;

    @Override
    public StoStockOutPlanVO getById(String id) {
        StoStockOutPlan stoStockOutPlan = stoStockOutPlanService.getById(id);
        StoStockOutPlanVO stoStockOutPlanVO = new StoStockOutPlanVO();
        BeanTools.copyProperties(stoStockOutPlanVO,stoStockOutPlan);
        return stoStockOutPlanVO;
    }

    /**
     * 获取出库计划详情
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public StoStockOutPlanVO getDetail(String id) throws Exception {
        return stoStockOutPlanService.getDetail(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(StoStockOutPlanVO stoStockOutPlanVO) throws Exception {
        //根据VIN查询是否存在未完成未作废的出库计划
        queryOutPlanIsExist(stoStockOutPlanVO);

        StoStockOutPlan stoStockOutPlan = new StoStockOutPlan();
        BeanTools.copyProperties(stoStockOutPlan,stoStockOutPlanVO);
        if(stoStockOutPlan.getStockOutPlanId() == null){
            String sop = codeCreateService.createCode("SOP", 4);
            stoStockOutPlan.setStockOutPlanNo(sop);
            stoStockOutPlan.setBillState("1");//单据状态新建
        }
        //根据VIN查询库位代码
        QueryWrapper<PmsVehicleStock> queryWrapper = new QueryWrapper();
        queryWrapper.eq("VIN",stoStockOutPlanVO.getVin());
        PmsVehicleStock pmsVehicleStock = vehicleStockMService.getOne(queryWrapper);
        if(pmsVehicleStock != null){
            stoStockOutPlan.setStorageCode(pmsVehicleStock.getStorageLocation());
        }
        //自动分配司机
        if(stoStockOutPlan.getStockOutDriver() == null){
            //1.查询今日上班司机,取今日出入库次数和最少的一位司机
            Date date = new Date();
            SimpleDateFormat dd = new SimpleDateFormat("dd");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String day = dd.format(date);
            String format = simpleDateFormat.format(date);
            StoDriverVO stoDriverVO1 = new StoDriverVO();
            stoDriverVO1.setWorkMonth(format);
            stoDriverVO1.setDay(Integer.parseInt(day));
            List<StoDriverVO> list = vehiclePdiBillService.queryTodayDriver(stoDriverVO1);
            if(list != null && list.size() > 0){
                for(StoDriverVO vo : list){
                    String workDays = vo.getWorkDays();
                    if(StringUtils.isNotEmpty(workDays)){
                        String[] split = workDays.split(",");
                        Boolean isContains = false;
                        for(String workDay : split){
                            if(workDay.equals(day)){
                                isContains = true;
                                break;
                            }
                        }
                        if(isContains){
                            stoStockOutPlan.setStockOutDriver(vo.getRfid());
                            stoStockOutPlan.setRfidDate(new Date());

                            //推送消息给司机
                            SatMessAddVO satMessAddVO = new SatMessAddVO();
                            satMessAddVO.setType("出库");
                            satMessAddVO.setInfo("有一个新的出库计划!");
                            satMessAddVO.setSalesConsultantNo(vo.getUserCode());
                            satMessAddVO.setReceiveRoleCode(DictConstant.USER_ROLE_DRIVER);
                            satMessService.pdaNewMess(satMessAddVO);
                        }
                    }
                }
            }
        }
        //通过VIN码查询批售单付款类型,现金则合格证随车,非现金则合格证不随车
        QueryWrapper<OrderVehicle> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("VIN",stoStockOutPlanVO.getVin());
        List<OrderVehicle> list = orderVehicleService.list(queryWrapper2);
        Integer isOnVehicle = null;
        if(list != null && list .size() > 0){
            OrderVehicle orderVehicle = list.get(0);
            String payway = orderVehicle.getPayway();
            if(com.alibaba.cloud.context.utils.StringUtils.isEmpty(payway) || !payway.equals("A")){
                isOnVehicle = 0;
            }
            else if(payway.equals("A")){
                isOnVehicle = 1;
            }
        }
        if(isOnVehicle != null){
            stoStockOutPlan.setIsOnVehicle(isOnVehicle);
        }
        stoStockOutPlanService.saveOrUpdate(stoStockOutPlan);
        //冻结所选车辆
        QueryWrapper<VehicleOffline> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("VIN",stoStockOutPlanVO.getVin());
        VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper1);
        if(vehicleOffline != null){
            vehicleOffline.setVehicleIsFrozen(1);
            vehicleOffline.setIsLock(1);
            vehicleOfflineService.saveOrUpdate(vehicleOffline);

            QueryWrapper<PmsVehicleStock> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("VIN",vehicleOffline.getVin());
            PmsVehicleStock vehicleStock = vehicleStockMService.getOne(queryWrapper3);
            if(vehicleStock != null){
                vehicleStock.setVehicleIsFrozen("1");
                vehicleStockMService.saveOrUpdate(vehicleStock);
            }

            //新增车辆冻结历史
            VehicleStockFrozenVO vehicleStockFrozenVO = new VehicleStockFrozenVO();
            vehicleStockFrozenVO.setFrozenReason("计划出库");
            vehicleStockMService.newFrozenHis("1",vehicleStockFrozenVO,vehicleOffline.getVin(),2);
        }
    }

    /**
     * //根据VIN查询是否存在未完成未作废的出库计划
     * @param stoStockOutPlanVO
     * @throws Exception
     */
    private void queryOutPlanIsExist(StoStockOutPlanVO stoStockOutPlanVO) throws Exception {
        QueryWrapper<StoStockOutPlan> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("VIN",stoStockOutPlanVO.getVin());
        queryWrapper4.ne("BILL_STATE",4);
        queryWrapper4.ne("BILL_STATE",5);
        if(StringUtils.isNotEmpty(stoStockOutPlanVO.getStockOutPlanId())){
            queryWrapper4.ne("STOCK_OUT_PLAN_ID",stoStockOutPlanVO.getStockOutPlanId());
        }
        List<StoStockOutPlan> list1 = stoStockOutPlanService.list(queryWrapper4);
        if(list1 != null && list1.size() > 0){
            throw new Exception("操作失败.VIN码:"+stoStockOutPlanVO.getVin()+"已存在未完成的出库计划!");
        }
    }

    @Override
    public void removeById(String id) {
    stoStockOutPlanService.removeById(id);
    }

    @Override
    public void delAndReset(List<String> list, Integer isDel,String userId) throws Exception{
        stoStockOutPlanService.delAndReset(list,isDel,userId);
    }

    @Override
    public void print(String stoStockOutPlanId) {
        stoStockOutPlanService.print(stoStockOutPlanId);
    }

    @Override
    public PageInfo vinList(PartnerVO vo,Integer pageNum ,Integer pageSize) {
        PageHelperPlus.startPage(pageNum,pageSize);
        List list = stoStockOutPlanService.vinList(vo);
        PageInfo<Object> pageInfo = new PageInfo<Object>(list);
        return pageInfo;
    }

    /**
     * 开始出库
     * @param stoStockScanVO
     * @throws Exception
     */
    @Override
    public void beginStockOut(StoStockScanVO stoStockScanVO) throws Exception {
        stoStockOutPlanService.beginStockOut(stoStockScanVO);
    }

    @Override
    public void complete(StoStockScanVO stoStockScanVO, LoginInfo loginInfo)throws Exception {
        stoStockOutPlanService.complete(stoStockScanVO,loginInfo);
    }

    @Override
    public void replace(StoStockOutPlanReplaceVO stoStockOutPlanReplaceVO,String userId)throws Exception {
        stoStockOutPlanService.replace(stoStockOutPlanReplaceVO,userId);
    }

    /**
     * 分配司机
     * @param stoStockOutDriverVO
     */
    @Override
    public void setDriver(StoStockOutDriverVO stoStockOutDriverVO,String userId) throws Exception{
        StoStockOutPlan stoStockOutPlan = stoStockOutPlanService.getById(stoStockOutDriverVO.getStockOutPlanId());
        if(stoStockOutPlan != null){
            stoStockOutPlan.setStockOutDriver(stoStockOutDriverVO.getStockOutDriver());
            stoStockOutPlan.setBillState("2");//分配司机
            stoStockOutPlan.setUpdateBy(userId);
            stoStockOutPlan.setRfidDate(new Date());
            stoStockOutPlanService.updateById(stoStockOutPlan);

            //推送消息给司机
            QueryWrapper<StoStorageStaff> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("RFID",stoStockOutDriverVO.getStockOutDriver());
            StoStorageStaff stoStorageStaff = stoStorageStaffService.getOne(queryWrapper);
            if(stoStorageStaff != null){
                SatMessAddVO satMessAddVO = new SatMessAddVO();
                satMessAddVO.setType("出库");
                satMessAddVO.setInfo("有一个新的出库计划!");
                satMessAddVO.setSalesConsultantNo(stoStorageStaff.getStorageStaffPhone());
                satMessAddVO.setReceiveRoleCode(DictConstant.USER_ROLE_DRIVER);
                satMessService.pdaNewMess(satMessAddVO);
            }
        }
        else {
            throw new Exception("操作失败,无法根据主键id:"+stoStockOutDriverVO.getStockOutPlanId()+"找到对应出库计划!");
        }
    }

    /**
     * 获取今日上班司机
     * @return
     * @throws Exception
     */
    @Override
    public List<StoStorageStaffDriverVO> getDriver(String planInOutDate) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        if(StringUtils.isNotEmpty(planInOutDate)){
            date = simpleDateFormat.parse(planInOutDate);
        }
        else{
            date = new Date();
        }
        SimpleDateFormat dd = new SimpleDateFormat("dd");
        String day = dd.format(date);
        String dayStr = String.valueOf(Integer.parseInt(day));
        String format = simpleDateFormat.format(date);
        StoStorageStaffDriverVO stoStorageStaffDriverVO = new StoStorageStaffDriverVO();
        stoStorageStaffDriverVO.setDay(Integer.parseInt(day));
        stoStorageStaffDriverVO.setWorkMonth(format);
        List<StoStorageStaffDriverVO> list = stoStockOutPlanService.getDriver(stoStorageStaffDriverVO);
        List<StoStorageStaffDriverVO> list1 = new ArrayList<>();
        if(list != null && list.size() > 0){
            for(StoStorageStaffDriverVO vo : list){
                String workDays = vo.getWorkDays();
                String[] split = workDays.split(",");
                Boolean isExist = false;
                for(String workDay : split){
                    if(workDay.equals(dayStr)){
                        isExist = true;
                        break;
                    }
                }
                if(isExist){
                    list1.add(vo);
                }
            }
        }

        return list1;
    }

    /**
     * 根据司机RFID获取出库计划
     * @param rfid
     * @return
     * @throws Exception
     */
    @Override
    public List<StoStockOutPlanVO> getOutPlanByRfid(String rfid) throws Exception {
        QueryWrapper<StoStockOutPlan> queryWrapper = new QueryWrapper();
        queryWrapper.eq("STOCK_OUT_DRIVER",rfid);
        queryWrapper.ne("BILL_STATE","5");//排除出库完成,作废的出库计划
        queryWrapper.ne("BILL_STATE","4");
        List<StoStockOutPlan> list = stoStockOutPlanService.list(queryWrapper);
        List<StoStockOutPlanVO> voList = new ArrayList();
        if(list != null && list.size() > 0){
            voList = BeanTools.copyListToList(list, StoStockOutPlanVO.class);
            for(StoStockOutPlanVO vo : voList){
                String storageCode = vo.getStorageCode();
                if(StringUtil.isNotEmpty(storageCode)){
                    QueryWrapper<StoManage> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("STORAGE_CODE", storageCode);
                    StoManage one = stoManageService.getOne(queryWrapper1);
                    if(one != null){
                        vo.setStorageName(one.getStorageFullName());
                    }
                }
            }
        }
        return voList;
    }

    @Override
    public PageInfo<StoStockOutPlanVO> findPageByVO(StoStockOutPlanVO stoStockOutPlanVO, Integer pageNum, Integer pageSize) {
        PageInfo<StoStockOutPlanVO> pageInfo = stoStockOutPlanService.pageByVo(stoStockOutPlanVO, pageNum, pageSize);
        return pageInfo;
    }

    /**
     * 逾期出库计划
     * @param stoStockOutPlanLateVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<StoStockOutPlanLateVO> lateStockOutPlan(StoStockOutPlanLateVO stoStockOutPlanLateVO, Integer pageNum, Integer pageSize) throws Exception {
        return stoStockOutPlanService.lateStockOutPlan(stoStockOutPlanLateVO,pageNum,pageSize);
    }

    @Override
    public List<StoStockOutPlanVO> export(StoStockOutPlanVO stoStockOutPlanVO) throws Exception {
        return stoStockOutPlanService.export(stoStockOutPlanVO);
    }

    /**
     * 根据VIN码查询出库计划
     * @param vin
     * @return
     * @throws Exception
     */
    @Override
    public List<StoStockOutPlanVO> planListByVin(String vin,String rfid) throws Exception {
        return stoStockOutPlanService.planListByVin(vin,rfid);
    }

}
